<?php
/* 
任务表格模块
审批类任务
 */
class TaskformAction extends IntesysAction {
	//初始化
	public function _initialize(){
		parent::_initialize();
		C('TOKEN_ON', false);
		$_POST['site_id'] = __SITEID__;
		$this->dao = D('Form');
	}
	//显示可选择表格，用户从这里选择一个电子表格
	public function index(){
	
		$this->pagesize = 21;
		$this->listmap = "site_id = ". __SITEID__;
		if($this->_param('keywords')){
			$keywords=$this->_param('keywords');
			//$_GET['keywords']=urlencode($this->_param('keywords'));
			$this->listmap.=" and topid =".$keywords;
			$this->keywords=$keywords;
		}
		$cat=D('formcategory')->where(array('site_id' => __SITEID__, 'status' => 1))->select();//查找分类
		$this->assign('candy',$cat);//分类渲染
		if($this->_get('id')){//设置了分类
			$id=$this->_get('id');
			$id[] = 0;
			//$this->listmap .= " and formcategory_id in(".implode(',', $id).")";
		}
		parent::_list();
		//将每一个列表都转化为实体并保存至list
		$this->initView();
		$list=$this->list;
		foreach($this->list as $k=>$v){
			$html = $this->dao -> where(array('id' => $v['id'])) -> createTaskForm($this-> view);
			$list[$k]['formtemplate']=$html;
		}
		$this->list=$list;
        //{$vo.formtemplate}
		$this->display();
	}
	
	
	public function add(){
		$this->display();
	}
	public function getTaskform(){
		$this->list=false;
		if($_GET['id']){
			$this->list=$this->dao->where('formcategory_id ='.$_GET['id'].' and site_id='.__SITEID__)->select();
		}
		$this->display();	
	}
	public function getTaskformline(){
		if(IS_POST && isset($_POST['member_id'])){
			$this->initView();
			$ret = D('Formline') -> saveformAll($_POST, $this->view);
			$this->success('保存成功！');
		}
		if($_GET['id']){
			$this->mit = microtime_float() * 10000+mt_rand(0,100);
			$this->list = D('Formline') -> where(array('id' => $_GET['id'])) -> getFieldArray($_GET['task_id']);
			$this->task=M('Task')->where(['id'=>$_GET['task_id'],'site_id'=>__SITEID__])->find();
			//$this->info=M('Mission')->where(['task_id'=>$_GET['task_id'],'task_hide_id'=>$_GET['task_id']])->getField('id')?false:M('Task')->where(['id'=>$_GET['task_id']])->find();
		}
		
		$this->display();	
	}
	//领取后填写表格
	public function getform(){
		$this->initView();
		if($this->_param('pid')){
			$this->assign('pid',$this->_param('pid'));
		}
		$this -> html = $this->dao -> where(array('id' => $this->_get('id'))) -> createTaskForm($this-> view);
		$this->display();
	}
	public function getnewform(){
		$this->initView();
		if($this->_param('pid')){
			$this->assign('pid',$this->_param('pid'));
		}
		$data=$this->dao -> where(array('id' => $this->_get('id')))->find();
		$this -> html = $this->dao -> where(array('id' => $this->_get('id'))) -> createTaskForm($this-> view);
		$this->display();
	}
	//规则页面获取表单
	public function getTemp(){
		if($this->_get('id')){
			$ruleDB=M('Integral_rule');
			$temp=$this->dao->where('id='.$this->_get('id'))->Field('id,formcategory_id,name,ruleidsource,template,ruleTemplate,approver,approvername')->find();
			$this->initView();
			$temp['template']=$temp['template']?$this->dao -> where(array('id' => $this->_get('id'))) -> createTaskForm($this-> view,NULL,1,2):'';
			$ret=unserialize($temp['ruleidsource']);
			unset($temp['ruleidsource']);
			/*foreach($temp as $k=>$v){
				foreach($v['rule'] as $ke=>$va){
					$ret[$k]['rule'][$ke]=$ruleDB->where('id='.$va[0])->find();
				}
			}*/
			$temp['status']=1;
			$temp['tbody']=$ret;
			echo(json_encode($temp));
		}	
	}
	//保存数据
	public function saveform() {
		$this->initView();
		$ret = D('Formline')->saveform($_POST,$this->view);
		if($ret === false){
			$this->error(D('Formline') -> getError());exit;
		}
	    $this->success('提交成功！您可以继续操作！');
	    exit;
		
		$formDB         	= D('Form');
		$taskDB         	= D('Task');
		$fieldDB        	= M('Field');
		$memberDB       	= D('Member');
		$missionDB      	= D('Mission');
		$scheduleDB     	= D('Schedule');
		$integral_ruleDB	= D('Integral_rule');
		$integral_typeDB	= D('Integral_type');
		$integral_ruletypeDB= D('Integral_ruletype');
		
		//验证表单的正确性
		if(isset($_POST['form_id']) && intval($_POST['form_id']) > 0){
		
			$formS = $formDB -> where(array('id' => intval($_POST['form_id']))) -> find();
		}else{
			$this->error('表单错误！');exit();
		}


		//限制提交周期
		if(intval($formS['cycle']) > 0){
			if(S('Mission_cycle')){
				$this->error($formS['cycle'].'只能提交一次！');exit();
			}
	
		}
		//如果标题为空
		if(!isset($_POST['title']) || (isset($_POST['title']) && $_POST['title'] == '')){
			$_POST['title'] = $formS['name'].'';
		}
		
		foreach($_POST as $k => $v){
			$fieldtype = $fieldDB -> where(array('f_name' => $k, 'site_id' => __SITEID__)) -> getField('f_type');
			if($fieldtype == 8){
				$_POST[$k] = strtotime($v);
			}
		}

        //获取页面提交的所有表单元素的数据集
        $data['object'] = serialize($_POST);
        //流水号
        $data['record'] = build_order_no();
        //任务类型 外部任务
        $data['missionType'] = 1;
        //任务状态 审核中
        $data['state'] = $_POST['status'];
        //标题
        $data['title'] = $_POST['title'];
        //问题详情
        $data['detail'] = isset($_POST['remark'])?$_POST['remark']:$_POST['detail'];
		//如果有规则的话，将规则名字和分数排列好，存入详情中
		if(isset($_POST['integral'])){
			$inteDetail=$integral_ruleDB->getIntegralName($_POST['integral']);
			$data['detail']=implode(' ',$inteDetail).$data['detail'];
		}
		//如果有规则源，获取规则
		if(isset($_POST['integral'])){
			$integral_id=0;
			foreach($_POST['integral'] as $value){
				foreach($value as $vo){
					if(isset($vo['id'])){
						$_POST['integralrule']=$_POST['integralrule']?$_POST['integralrule']:$vo['id'];
					}
				}
			}
		}
		//如果有规则，获取根分类，用于统计
		if($_POST['integralrule']){
			$data['rule_topid']=$integral_ruletypeDB->getTopId($integral_ruleDB->where(['id'=>$_POST['integralrule']])->getField('type_id'));
		}
		
		//结束时间
//		$data['endtime']=strtotime($_POST['endtime']);
        //当前表单ID
        $data['form_id'] = $_POST['form_id'];
		//是否临时任务（0非1是）
		$data['temptask']=$_POST['temptask']?$_POST['temptask']:0;

		$data['formcategory_id'] = $formS['formcategory_id'];
		
		$data['particular'] = $formS['particular'];
        //创建任务的时间
        $data['createtime'] = time();
		
		$data['approver'] = $_POST['approver'];
		$data['formula'] = $_POST['formula'];
		$data['approvername'] = $_POST['approvername'];
		
        //当前站点ID
        $data['site_id'] = __SITEID__; 
		
		//任务ID
		if($_POST['is_add'] == 1){
		    $data['task_id'] = (int)$_POST['task_id'];
		}
		if($_REQUEST['pid']){
			$data['pid'] = (int)$this->_param('pid');
		}
		
		
		//如果有传值就为传值 ，否则为当前 用户ID
		$data['member_id'] = empty($this->memberInfo['id'])?0:intval($this->memberInfo['id']);
		$data['member_id']= empty($_POST['member_id'])?$data['member_id']:$_POST['member_id'];
		
		$data['approver_id']=intval($this->memberInfo['id']);
		$data['approvername']=$this->memberInfo['name'];
		
		//如果有传值就为传值 ，否则为当前 用户名
		$data['proposername'] = $memberDB->where('id='.$data['member_id'])->getField('name');
		
		if($_POST['temp']){
			$data['temptask']=1;
		}
		
		$this -> initView();
		$data['formtemplate'] = $formDB -> where(array('id' => $_POST['form_id'])) -> createTaskForm($this->view, $_POST, 0);
		
		if($data['temptask']!=0){
			$data['member_id']='0'; 
			$data['proposername']='';
		}
		//如果是添加那么将当前用户ID传值给创建人ID
		if($_POST['is_add'] == 1){
			$data['user_id']=$this->UserInfo;
		}
		$data[C('TOKEN_NAME')] = $_SESSION[C('TOKEN_NAME')];


		$data['starttime']=$_POST['starttime']?$_POST['starttime']:time();
		$data['endtime']=$_POST['endtime']?$_POST['endtime']:time();

		$this->initView();
		D('Formline')->saveform($data,$this->view);
//		//如果是在任务添加工作的话，将任务的负责人，创建人，或者是父工作的负责人也转为审核人
//		if(intval($_POST['task_id']) > 0){
//			$task=$taskDB->where('id='.$_POST['task_id'])->find();
//			$data['reviewer_id']=$task['member_id'];
//			$data['approver_id'] = 0;
//			$data['approver'] = '';
//			$data['approvername']=$task['member_name'];
//
//			//如果创建者不是负责人pid > 0
//			if(intval($_POST['pid']) > 0){
//				$pm = $missionDB -> where(array('id' => intval($_POST['pid']))) -> find();
//				if($pm){
//					$data['reviewer_id']=$pm['member_id'];
//			        $data['approver_id'] = 0;
//			        $data['approver'] = '';
//			        $data['approvername']=$pm['proposername'];
//				}
//			}
//			//$data['other_id']=isset($data['pid'])?$task['creator_id'].$missionDB->getParentMember($data['pid']):0;
//		}
//
//
//		//个人信息登记指定积分管理员审批
//		if($formS['particular'] == 2){
//			$approver = getManagerList();
//			//$approver[] = 0;
//			if(!empty($approver)){
//				$data['approver'] = ','.implode(',', $approver).',';
//			    $data['approvername'] = array();
//				$approvername = $memberDB->where('id in ('.implode(',',$approver).')')->Field('name') -> select();
//				foreach($approvername as $k => $v){
//					$data['approvername'][] = $v['name'];
//				}
//				$_POST['state'] = 0;
//				$_POST['is_add'] = 1;
//				$data['approvername'] = implode(',', $data['approvername']);
//			}
//		}
//
//		Vendor('Pinyin.pinyin');
//		$py=new cn2pinyin();
//		$data['memberstring']=$py->get($data['proposername']);
//
//        //创建任务数据对象
//        $cdata = $missionDB->create($data);
//		if(!$cdata){
//			$this->error($missionDB -> getError());exit;
//		}
//
//
//		if($_POST['is_add'] == 1){
//
//			$mid = $missionDB->add();
//			if($mid > 0){
//				//更新任务的总分数
//			    $this -> initView();
//			    $integralret = $missionDB -> where(array('id' => $mid)) -> geteventIntegral($this->view);
////				var_dump(serialize($integralret));exit;
//				//var_dump($integralret);exit;//array(1) { [209583]=> array(2) { ["name"]=> string(6) "浩哥" ["integral"]=> array(1) { ["Binte"]=> int(0) } } }
//				$missionDB -> where(array('id' => $mid))->setField('integralret',serialize($integralret));
//				$taskDB -> where(array('id' => $data['task_id'], 'site_id' => __SITEID__)) -> SetEventIntegral();
//			}
//		}else{
//			$taskid = $missionDB -> where(array('id' => $_POST['id'])) -> getField('task_id');
//
//			$this -> initView();
//			$integralret = $missionDB -> where(array('id' => $_POST['id'])) -> geteventIntegral($this->view);
//
//			$taskDB -> where(array('id' => $taskid, 'site_id' => __SITEID__)) -> SetEventIntegral();
//			$mid = $missionDB -> where(array('id' => $_POST['id'])) ->save($data);
//			//重新写入积分总数
//			$integralret = $missionDB -> where(array('id' => $_POST['id'])) -> geteventIntegral($this->view);
//			$missionDB -> where(array('id' => $_POST['id']))->setField('integralret',serialize($integralret));
//			$taskDB -> where(array('id' => $taskid, 'site_id' => __SITEID__)) -> SetEventIntegral();
//
//		}
//
//        if ($mid !== false) {
//			if(intval($formS['cycle']) > 0){
//				S('Mission_cycle', 1, $formS['cycle']);
//			}
//			if($data['task_id'] > 0){
//				$taskDB -> where(array('id' => $data['task_id'], 'site_id' => __SITEID__)) -> updateprogress();
//			}
//			//如果是积分事件上面加分则直接审批(并添加审批记录)，直接通过，直接加分！
//			if($_POST['access']=='Integral_log'){
//				$missionDB-> where(array('id' => $mid)) ->setField('state','3');
//				$data['mission_id']=$mid;
//				if($data['particular']!=0&&$data['particular']!=2){
//					$data['name']=$data['proposername'];
//					$data['starttime']=$_POST['starttime']?$_POST['starttime']:time();
//					$data['endtime']=$_POST['endtime']?$_POST['endtime']:time();
//					D('Attendence')->data($data)->add();
//				}
//				$ret=$scheduleDB->formatAdd($data,$integralret);
//				$this->initView();
//				$r=$missionDB-> where(array('id' => $mid)) -> createevent($this-> view);
//				if($r===false){
//					$this->error('当前分配的积分超出了用户的积分权限');
//				}
//			}
			
			//如果表格有变动，则过虑表格并发送提醒信息给拥有者
			$str=htmlspecialchars_decode($data['formtemplate']);
			$str = "表格有变动:".preg_replace( "@<style(.*?)</style>@is", "", $str ); 
	
			//preg_match_all('|value="(.*)"|isU',$str,$match);
			//preg_replace('/(<img).+(src="?.+)images/(.+.(jpg|gif|bmp|bnp|png)"?).+>/i',"${1} ${2}uc/images/${3}>",$str);
			//$str=preg_replace('/(<input).+(value="?)/i',"",$str);
			//$str= preg_replace("/<(.*?)>/","",$str); 
			$str= preg_replace("/<input(.*?)>/","",$str);
			$str= strip_tags($str); 
			$str= preg_replace("/\&nbsp;/","",$str); 
			$str= preg_replace("/\&quot;/","",$str);
			$str= preg_replace("/保存/","",$str);
			
	      
          $this->success('保存成功');
			//A('Intesys/Info')->sendMsg();
	
		$tomemberid=M('Mission')->where('form_id='.$data['form_id'])->field('member_id')->find();
			
		D('Info')->sendMsg([['content'=>$str,'mode'=>C('MSG_TYPE'),'tomemberid'=>$tomemberid['member_id'],'type'=>'remind']]);

//		D('Formline')->saveform($data,$this->view);
           
//        }
    }
	//选择表格列表
	public function select(){
		$this->pagesize = 12;
		
		$this->listmap = "site_id = ". __SITEID__;
		if($this->_get('selected') && $this->_get('selected') != ''){
			$this->pagesize = 100;
			$this->listmap = "id in(".$this->_get('selected').")";
		}
		if($this->_param('keywords')){
			$keywords=$this->_param('keywords');
			$_GET['keywords']=urlencode($this->_param('keywords'));
			$this->listmap.=" and title like '%{$keywords}%'";
			$this->keywords=$keywords;
		}
		parent::_list();

		$this->display();
	}
	
	public function modify(){
		$Form = M('form');
		$res = $Form ->where(array('id'=>$this->_get('id'))) ->find();
		$res['rule'] = trim($res['ruleids'],',');
		$this -> assign('form',$res);
		//$this->formcategory = M('Formcategory') -> where(array('site_id' => __SITEID__)) -> order('sort, id desc') -> select();
		$this->formcategorylist = D('Formcategory') -> getList();
		parent::edit();
	}

	//重新编辑方法
	public function edit(){
		$id = $this->_get('id');//获取表单的ID
		//查询该表单下的字段表的集合数据
		$Field = M('Field');
		$fields = $Field ->where(array('form_id' => $id)) -> select();
		$this -> assign('list',$fields);//渲染字段数据集
		//查询该表单的详细信息
		$Form = M('form');

		$res = $Form ->where(array('id'=>$id)) ->find();
		$res['approver'] = trim($res['approver'],',');
		$res['rule'] = trim($res['ruleids'],',');



		$this->InteType = M('Integral_type') -> where(array('site_id' => __SITEID__)) -> select();


		$this->formcategory = M('Formcategory') -> where(array('site_id' => __SITEID__)) -> order('sort, id desc') -> select();


		//dump($res);
		$this -> assign('form',$res);
		parent::edit();
	}
	//添加一个从新建规则页面传来的新的表单并转化选项
	public function addForm(){

		if(IS_POST){
			foreach($_POST['groupRule'] as $k=>$v){
				$arr[$k]['name']=$_POST['groupName'][$k];
				$arr[$k]['type']=$_POST['groupType'][$k];
				$arr[$k]['rule']=$v;
			}
			/*foreach($_POST['groupName'] as $k=>$v){
				$arr[$k]['name']=$v;
				$arr[$k]['type']=$_POST['groupType'][$k];
				$arr[$k]['rule']=$_POST['groupRule'][$k];
			}*/
			
			$_POST['ruleidsource']=serialize($arr);
			//$_POST['formula']='';
			if($_POST['id']){
				parent::update();
			}else{
				parent::insert();
			}
		}
	}

	public function update(){
		$_POST['approver'] = ','.implode(',',$_POST['member_id']).',';
		$_POST['approvername'] = implode(',',$_POST['member_name']);
		$_POST['ruleids'] = ','.implode(',',$_POST['rule_id']).',';
		
		//当修改表格的时候，如果有选择分类，则将根分类一起插入
		if(isset($_POST['formcategory_id'])){
			$_POST['topid']=D('Formcategory')->getTopid($_POST['formcategory_id']);
		}
		
		//$this->initView();
		//$_post['resultTemplate'] = D('Form') -> where(array('id' => $_POST['id'])) -> createTaskForm($this->view);
		
		
		parent::update(array(), U('index'));
	}
	
	
	/*//多提交表单方法  页面需要传过来form_id
  public function lwntest()
    {
		if(empty($_GET['form_id'])){
        $_GET['form_id'] = 409;
		}
        $Task = D('Task');
        $html = D('field')->where(' form_id=' . $_GET['form_id'])->select();
        // 转换html
        $Field = $Task->TaskMulti($html);
        $this->assign('f_data', $Field);
        $this->assign('form_id', $_get['form_id']);
        
        if (! IS_POST) {
            $this->display();
        } else {
            
            // 获取积分管理员的列表
            $isAdmin = getManagerList();
            // 拼起来
            foreach ($isAdmin as $akey => $aval) {
                $admin .= $aval . ",";
            }
                        
            $Task = D('Task');
            $data = $_POST;
            $_POST = array();
            
            foreach ($data as $pkey => $pval) {
                for ($i = 0; $i < count($pval); $i ++) {
                    if (is_array($pval)) {
                        $_POST[$i][$pkey] = $pval[$i];
                    } else {
                        $_POST[$i][$pkey] = $pval;
                    }
                }
            }
    
            // approver审批人必须要传过来
            foreach ($_POST as $key => $val) {
                $_POST = array();
                $_POST = $val;
                $_POST['is_add'] = 1;
                $_POST['status'] = - 1;
                $_POST['approver'] = $admin;
                // $this->saveform()
                $text[] = $Task->transition($html, $_POST);
            }
	dump($text);
        }
	
    }*/
	 public function tablePost()
    {
        if (empty($_POST['form_id'])) {
            $_POST['form_id'] = 409;
        }
        $Task = D('Task');
        $html = M('field')->where('form_id=' . $_POST['form_id'])->select();
		dump($html);
        $Field = $Task->TaskMulti($html);
        $this->assign('f_data', $Field);
		$this->assign('form_id',$_POST['form_id']);
        $this->display();
    }

    public function arrayPost()
    {
		$Task = D('Task');
        $html = M('field')->where('form_id=')->select();
        $Field = $Task->TaskMulti($html);
		$Task = D('Task');
        $data = array();
		   /*$isAdmin = getManagerList();
            // 拼起来
            foreach ($isAdmin as $akey => $aval) {
                $admin .= $aval . ",";
            }
		    */
        foreach ($_POST as $pkey => $pval) {
            for ($i = 0; $i < count($pval); $i ++) {
                if (is_array($pval)) {
                    $data[$i][$pkey] = $pval[$i];
                } else {
                    $data[$i][$pkey] = $pval;
                }
            }
        }
        // approver审批人必须要传过来
        foreach ($data as $key => $val) {
		  /*$_POST['is_add'] = 1;
          $_POST['status'] = - 1;
		  $_POST['approver'] = $admin;*/
                $_POST = array();
                $_POST = $val;
            // $this->saveform()
            $text[] = $Task->transition($Field, $_POST);
        }
        dump($text);
    }
}